﻿// This code is released under the BSD license.
namespace PugLib.IO
{
    using System;
    using System.Globalization;
    using System.IO;

    public class FriendlySize
    {
        private readonly long _length;
        private readonly String[] _sizes = { "B", "KB", "MB", "GB", "TB" };

        public FriendlySize(FileInfo file)
        {
            _length = file.Length;
        }

        public FriendlySize(String file)
            : this(new FileInfo(file))
        {
        }

        public FriendlySize(long size)
        {
            _length = size;
        }

        public override string ToString()
        {
            double len = _length;
            int order = 0;
            while (len >= 1024 && order + 1 < _sizes.Length)
            {
                order++;
                len = len / 1024;
            }
            return String.Format(CultureInfo.InstalledUICulture, "{0:0.##} {1}", len, _sizes[order]);
        }
    }
}